<template>
  <div class="paper-detail">
    <template v-if="!isPaperRegroup">
      <QuestionTree
        ref="questionTree"
        class="paper-left"
        :show-question-mode="false"
        :show-select-all="true"
        :pager-repos-id="$route.query.courseId"
        @tree-node-click="handleNodeClick"
        @on-ready="onReadyRepos"
      ></QuestionTree>
    </template>
    <div class="paper-right">
      <div class="paper-views">
        <section-box v-if="!isPaperRegroup" title="选择考核范围" style="margin-bottom: 25px">
          <template slot="tools">
            <!-- <el-link type="primary" icon="el-icon-folder-checked" @click="addAllScope">全部添加</el-link> -->
            <el-link type="danger" icon="el-icon-delete-solid" :disabled="isEdit" @click="clearScope">清空</el-link>
          </template>

          <div class="assessment-scope-list">
            <el-tag
              v-for="(item, index) in assessmentScope"
              :key="item.id"
              class="tag-item"
              :closable="true"
              type="info"
              effect="dark"
              @close="deleteScopeItem(index)"
            >
              {{ item.nodeName }}
            </el-tag>
          </div>
        </section-box>

        <section-box v-if="isPaperRegroup" title="已选择的试卷" style="margin-bottom: 25px">
          <div class="assessment-scope-list">
            <el-tag v-for="(item, index) in paperNames" :key="index" class="tag-item" :closable="false" type="info"
                    effect="dark">
              {{ item }}
            </el-tag>
          </div>
        </section-box>

        <section-box title="试卷设置" style="margin-bottom: 25px">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="22">
                <el-form-item label="考核方案" prop="paperName">
                  <el-input v-model="form.paperName" placeholder="请输入考核方案" maxlength="50"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="试题份数" prop="generateNum">
                  <el-input-number
                    v-model="form.generateNum"
                    :disabled="isPaperRegroup"
                    :precision="0"
                    :min="1"
                    :max="10000"
                    style="width: 120px"
                  ></el-input-number>
                </el-form-item>
              </el-col>
              <el-col v-if="form.generateNum > 1" :span="14">
                <el-form-item label="重复率" prop="generateRepeat">
                  <el-input-number
                    v-model="form.generateRepeat"
                    :precision="2"
                    :step="0.01"
                    :min="0"
                    :max="0.99"
                    style="width: 120px"
                  ></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <!--              <el-col :span="10">-->
              <!--                <el-form-item label="显示密封线" prop="paperSealLine">-->
              <!--                  <el-switch v-model="form.paperSealLine" active-color="#1890ff" inactive-color="#999" active-value="1" inactive-value="0">-->
              <!--                  </el-switch>-->
              <!--                </el-form-item>-->
              <!--              </el-col>-->
              <el-col :span="10">
                <el-form-item label="考试时长" prop="paperTime">
                  <el-input-number
                    v-model="form.paperTime"
                    :precision="0"
                    :min="0"
                    :max="1000"
                    :step="10"
                    style="width: 120px"
                  ></el-input-number>
                  <span style="margin-left: 10px">分钟</span>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="试卷总分" prop="paperTotalScore">
                  <el-input-number
                    v-model="form.paperTotalScore"
                    :precision="0"
                    :min="1"
                    :max="500"
                    :step="1"
                    style="width: 120px"
                  ></el-input-number>
                  <span style="margin-left: 10px">分</span>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="难度系数" prop="generateEasy">
                  <el-input-number
                    v-model="form.generateEasy"
                    :precision="0"
                    :min="60"
                    :max="75"
                    :step="1"
                    style="width: 120px"
                  ></el-input-number>
                  <span style="margin-left: 10px">%（范围：60%-75%）</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="注意事项" prop="paperAttention">
                  <el-input
                    v-model="form.paperAttention"
                    type="textarea"
                    :rows="4"
                    maxlength="500"
                    placeholder="请输入注意事项"
                    style="width: 100%"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>
        </section-box>

        <section-box v-if="!isPaperRegroup && isEdit" title="题型及数量" style="margin-bottom: 25px">
          <QuestionTypeTable
            v-if="form.generateDetails && form.generateDetails.length > 0"
            ref="questionTypeTable"
            :loading="dialogLoading"
            :generate-details="form.generateDetails"
          ></QuestionTypeTable>
        </section-box>

        <div style="text-align: center">
          <!-- <el-button v-if="isEdit" type="primary" @click="editGenerate">修改组卷</el-button> -->
          <el-button v-if="isEdit" type="primary" @click="nextStep">修改组卷</el-button>
          <el-button v-else type="primary" @click="nextStep">智能组卷</el-button>
        </div>
      </div>
    </div>
    <QuestionTypeDialog ref="questionTypeDialog" :loading="dialogLoading"
                        @confirm="confirmGenerate"></QuestionTypeDialog>
  </div>
</template>
<script>
  import QuestionTree from './QuestionTree.vue'
  import SectionBox from './SectionBox.vue'
  import PaperAttr from './PaperAttr.vue'
  import QuestionTypeDialog from './QuestionTypeDialog.vue'
  import QuestionTypeTable from './QuestionTypeTable.vue'
  import { addJuanGenerate, getJuanGenerate, queryPaperNamesByIds, updateJuanGenerate } from '@/api/juan/juanGenerate'
  import { decode } from 'js-base64'

  export default {
    components: { QuestionTree, SectionBox, PaperAttr, QuestionTypeDialog, QuestionTypeTable },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        reposId: null,
        generateId: null,
        loading: false,
        scopeType: 2,
        assessmentScope: [],
        form: {
          generateNum: 1,
          paperName: '',
          paperAttention: '',
          paperSealLine: '1',
          paperTime: 120,
          generateRepeat: 0.99,
          paperTotalScore: 1,
          generateEasy: 60
        },
        rules: {
          generateNum: [{ required: true, message: '请输入试题份数', trigger: ['blur', 'change'] }],
          generateRepeat: [{ required: true, message: '请输入重复率', trigger: ['blur', 'change'] }],
          paperName: [{ required: true, message: '请输入试卷标题', trigger: ['blur', 'change'] }],
          paperSealLine: [{ required: true, message: '请选择是否显示密封线', trigger: ['blur', 'change'] }],
          paperTime: [{ required: true, message: '请输入考试时长', trigger: ['blur', 'change'] }],
          generateEasy: [{ required: true, message: '请输入难度系数', trigger: ['blur', 'change'] }],
          paperTotalScore: [{ required: true, message: '请输入考试总分', trigger: ['blur', 'change'] }],
          paperAttention: [{ required: false, message: '请输入注意事项', trigger: ['blur', 'change'] }]
        },

        dialogLoading: false,

        isPaperRegroup: false,
        paperIds: [],
        courseId: undefined,
        paperNames: [],
        cascader: {}
      }
    },
    watch: {
      reposId: {
        handler(val) {
          if (val) {
            setTimeout(() => {
              this.showQuestionType() // 回显题型及数量
            }, 500)
          }
        },
        deep: true,
        immediate: true
      }
    },
    created() {
      if (this.isEdit) {
        this.generateId = this.$route.query.generateId
        if (this.generateId) {
          this.fetchData()
        } else {
          this.$router.go(-1)
        }
      } else {
        let paperIdDecode = this.$route.query.paperIds
        let courseId = this.$route.query.courseId
        if (paperIdDecode) {
          let paperIdstr = decode(paperIdDecode)
          let paperIds = paperIdstr.split(',')
          let courseIdstr = decode(courseId)
          if (paperIds && paperIds.length > 0) {
            this.isPaperRegroup = true
            this.paperIds = paperIds
            this.courseId = courseIdstr

            this.form.generateNum = 1
            this.form.generateRepeat = 1
            this.renderPaper()
          }
        }
      }
    },
    methods: {
      fetchData() {
        this.loading = true
        getJuanGenerate(this.generateId)
          .then((res) => {
            this.loading = false
            this.form = res.data
            this.form.generateEasy = res.data.generateEasy*100;
            this.$forceUpdate();
            if (res.data.generateScopeType == '3') {
              this.isPaperRegroup = true
              this.paperIds = res.data.generateScope.split(',')
              this.paperNames = res.data.generateScopeNames
            } else {
              let generateScope = res.data.generateScope.split(',')
              this.assessmentScope = generateScope.map((item, index) => {
                return {
                  nodeName: res.data.generateScopeNames[index],
                  id: item
                }
              })
            }
          })
          .catch(() => {
            this.loading = false
          })
      },
      renderPaper() {
        queryPaperNamesByIds(this.paperIds.join(','))
          .then((res) => {
            this.paperNames = res.data
          })
          .catch()
      },
      onReadyRepos(data) {
        this.reposId = data.reposId
      },
      handleNodeClick(data) {
        // if (!this.isEdit) {}
        let dataIndex = this.assessmentScope.findIndex((item) => {
          return item.id === data.id
        })
        if (dataIndex === -1) {
          this.assessmentScope.push(data)
        }
      },
      clearScope() {
        this.$confirm('您确定要清空吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.assessmentScope = []
          })
          .catch(() => {
          })
      },
      deleteScopeItem(index) {
        this.assessmentScope.splice(index, 1)
      },
      nextStep() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.isPaperRegroup) {
              if (this.paperIds.length > 0) {
                this.$refs.questionTypeDialog.open({
                  type: 'paperRegroup',
                  ids: this.paperIds
                })
              } else {
                this.$message({
                  message: '请先选择试卷',
                  type: 'warning'
                })
              }
            } else {
              if (this.reposId) {
                let ids = this.assessmentScope.map((item) => {
                  return item.id
                })
                this.$refs.questionTypeDialog.open({
                  type: 'questionRepos',
                  reposId: this.reposId,
                  courseId: this.$route.query.courseId,
                  ids: ids
                })
              } else {
                this.$message({
                  message: '请先选择题库',
                  type: 'warning'
                })
              }
            }
          }
        })
      },
      confirmGenerate(data) {
        if (this.isPaperRegroup) {
          if (this.paperIds.length <= 0) {
            this.$message({
              message: '请先选择试卷',
              type: 'warning'
            })
          }
        } else {
          if (!this.reposId) {
            this.$message({
              message: '请先选择题库',
              type: 'warning'
            })
          }
        }

        let ids = this.assessmentScope.map((item) => {
          return item.id
        })
        this.form.generateEasy = this.form.generateEasy / 100
        let options = {
          ...this.form,
          generateDetails: data
        }

        if (this.isPaperRegroup) {
          options.generateScopeType = 3
          options.generateScope = this.paperIds.join(',')
          options.courseId = this.courseId
        } else {
          options.courseId = this.$route.query.courseId
          options.reposId = this.reposId
          options.generateScopeType = this.scopeType
          options.generateScope = ids.join(',')
        }

        if (options.generateNum === 1) {
          options.generateRepeat = 1
        }

        this.dialogLoading = true
        if (!this.isEdit) {
          addJuanGenerate(options)
            .then((res) => {
              this.dialogLoading = false
              this.$refs.questionTypeDialog.close()
              this.$message({
                message: '组卷创建成功',
                type: 'success'
              })
              setTimeout(() => {
                this.$router.push('/juanGenerate/juanGenerate')
              }, 1000)
            })
            .catch(() => {
              this.dialogLoading = false
            })
        } else {
          updateJuanGenerate(options)
            .then((res) => {
              this.dialogLoading = false
              this.$refs.questionTypeDialog.close()
              this.$message({
                message: '组卷修改成功',
                type: 'success'
              })
              setTimeout(() => {
                this.$router.push('/juanGenerate/juanGenerate')
              }, 1000)
            })
            .catch(() => {
              this.dialogLoading = false
            })
        }

        // console.log(JSON.parse(JSON.stringify(options)));
      },
      editGenerate() {
        let options = {
          ...this.form
        }

        if (this.isPaperRegroup) {
          options.generateScopeType = 3
          options.generateScope = this.paperIds.join(',')
        } else {
          let ids = this.assessmentScope.map((item) => {
            return item.id
          })
          options.generateScopeType = this.scopeType
          options.generateScope = ids.join(',')
        }

        delete options.generateDetails

        if (options.generateNum === 1) {
          options.generateRepeat = 1
        }

        this.dialogLoading = true

        updateJuanGenerate(options)
          .then((res) => {
            this.dialogLoading = false
            this.$message({
              message: '组卷修改成功',
              type: 'success'
            })
            setTimeout(() => {
              this.$router.push('/juanGenerate/juanGenerate')
            }, 1000)
          })
          .catch(() => {
            this.dialogLoading = false
          })
      },
      showQuestionType() {
        console.log(this.form)
        if (this.reposId && this.form.generateDetails && this.form.generateDetails.length > 0) {
          let ids = this.assessmentScope.map((item) => {
            return item.id
          })
          this.$refs.questionTypeTable.open({
            type: 'questionRepos',
            reposId: this.reposId,
            courseId: this.$route.query.courseId,
            ids: ids
          })
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .paper-detail {
    position: relative;
    width: 100%;
    height: calc(100vh - 50px);
    background-color: #f4f4f8;
    padding: 20px;
    box-sizing: border-box;
    display: flex;
    align-items: stretch;

    .paper-left {
      flex-shrink: 0;
      height: 100%;
      width: 300px;
      margin-right: 24px;
    }

    .paper-right {
      height: 100%;
      width: 0;
      flex: 1;
      overflow-y: auto;
    }
  }

  .hasTagsView {
    .paper-detail {
      height: calc(100vh - 84px);
    }
  }

  .assessment-scope-list {
    display: flex;
    flex-wrap: wrap;
    margin: -10px;

    .tag-item {
      margin: 10px;
      background-color: #ebedf2;
      font-size: 16px;
      color: #282f47;
      border: none;
      height: 36px;
      line-height: 36px;
      padding: 0 14px;

      ::v-deep {
        .el-icon-close {
          background-color: #aeb3b7;

          &:hover {
            background-color: #1890ff;
          }
        }
      }
    }
  }

  .condition-list {
    .condition-item {
      display: flex;
      margin-top: 20px;

      &:first-child {
        margin-top: 0;
      }

      .title-label {
        height: 32px;
        line-height: 32px;
        font-size: 16px;
        color: #1890ff;
        flex-shrink: 0;
        margin-right: 20px;
      }

      .condition-children {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        margin: -6px;

        .condition-tag {
          min-width: 80px;
          height: 32px;
          border-radius: 4px;
          font-size: 16px;
          color: #282f47;
          text-align: center;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          margin: 6px;

          &:hover {
            background-color: rgba($color: #1890ff, $alpha: 0.5);
            color: #fff;
          }

          &.active {
            background-color: #1890ff;
            color: #fff;
          }
        }
      }
    }
  }

  .questions-numbers {
    margin: -10px -16px;
    display: flex;
    flex-wrap: wrap;

    .number-item {
      margin: 10px 16px;
      display: flex;
      align-items: center;

      .number-label {
        width: 70px;
        font-size: 16px;
        color: #282f47;
        text-align: right;
        margin-right: 10px;
      }

      .number-input {
        width: 110px;
      }
    }
  }
</style>
